﻿using Microsoft.Extensions.Logging;
using System.Net;
using System.Net.Sockets;
using TcpJsonService.Core;

namespace TcpJsonService.Fvs
{
    public class VirtualFvsChannel(IPEndPoint remoteEndPoint, ILogger logger) : TcpChannel(remoteEndPoint, logger)
    {
        /// <summary>
        /// 获取指定时间转换为utc时间的时间戳
        /// </summary>
        /// <param name="dateTime">时间</param>
        /// <returns>时间戳</returns>
        private static long ToUtcTimeStamp()
        {
            return Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds);
        }

        private void SendProtocol(ushort id, object content)
        {
            List<byte> contentBuffer = ByteFormatter.Serialize(content);
            ProtocolHead head = new()
            {
                Tag = ProtocolHead.HeadTag,
                Id = id,
                ContentSize = Convert.ToUInt16(contentBuffer.Count),
                TimeStamp = ToUtcTimeStamp(),
            };
            List<byte> buffer = ByteFormatter.Serialize(head);
            buffer.AddRange(contentBuffer);
            Send([.. buffer]);
        }

        public void Test(ushort port, int id)
        {
            List<byte> buffer = [0x81, Convert.ToByte(id), 0x0b, 0, 0, 0xff];

            ShootRequest request = new()
            {
                Port = port,
                ControllerId = id,
                ProtocolId=0x0b,
                Buffer = [.. buffer]
            };

            SendProtocol(ShootRequest.Id, request);
        }

        public void Test1()
        {
            CollectStatusRequest request = new()
            {
            };

            SendProtocol(CollectStatusRequest.Id, request);
        }

        protected override bool Unpack(Socket socket, List<byte> buffer, ref int offset)
        {
            ProtocolHead head = new();
            ByteFormatter.Deserialize(head, [.. buffer]);
            if (head.Id == ShootResponse.Id)
            {
                ShootResponse response = new();
                ByteFormatter.Deserialize(response, [.. buffer], ProtocolHead.HeadSize);
            }
            else if(head.Id==CollectStatusResponse.Id)
            {
                CollectStatusResponse response = new();
                ByteFormatter.Deserialize(response, [.. buffer], ProtocolHead.HeadSize);
                foreach(var controller in response.Controllers)
                {
                    _logger.LogInformation($"{controller.ControllerId} {new IPAddress(controller.RemoteIp)} {controller.RemotePort} {new IPAddress(controller.LocalIp)} {controller.LocalPort} {controller.Transmit} {controller.Receive}");
                }
            }
            offset += buffer.Count;
            return true;
        }
    }
}
